/*   Copyright (C) 2008  Jeroen v. Schagen & Youri Lima
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using Engine.Connection;
using Engine.Connection.Client;

namespace Client
{
    public partial class ChatForm : Form
    {
        // Connection
        private TCPClient connection;

        public ChatForm()
        {
            InitializeComponent();

            // Retrieve connection
            connection = new TCPClient("Chat");

            // Attach event
            connection.DataRecieved += new PackageEventHandler(connection_DataRecieved);

            // Disable cross thread exceptions
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        public static void Main(string[] args)
        {
            // Configure logger
            Engine.Logger.Configure("data/config/log4net.cfg.xml");

            // Run application
            Application.Run(new ChatForm());
        }

        // Append message
        public void AppendMessage(string message)
        {
            String timestamp = "[" + DateTime.Now.Hour + ":" + DateTime.Now.Minute + ":" + DateTime.Now.Second + "] ";
            txfMessages.AppendText(timestamp + message + "\r\n");
        }

        // Client callbacks
        private void connection_DataRecieved(object sender, Packet package)
        {
            // Decode package
            byte[] buffer = package.DataBuffer;
            char[] chars = new char[buffer.Length];

            Decoder d = Encoding.ASCII.GetDecoder();
            d.GetChars(buffer, 0, buffer.Length, chars, 0);

            String data = new String(chars);

            // Message box
            if (data.StartsWith("mb"))
            {
                String[] split = data.Split(' ');
                String message = "";

                if (split.Length > 1)
                {
                    for (int i = 1; i < split.Length; i++)
                    {
                        message += split[i] + " ";
                    }
                }

                MessageBox.Show("Admin announcement:\r\n" + message);
            }

            // Kill client
            else if (data.StartsWith("kill"))
            {
                this.Close();
            }

            // Display message
            else
            {
                AppendMessage(data);
            }
        }

        // Form callbacks
        private void btnSend_Click(object sender, EventArgs e)
        {
            if (connection.Connected && txfMessage.Text != "")
            {
                String message = txfMessage.Text;

                connection.Send(Encoding.ASCII.GetBytes(message));
                txfMessage.Text = "/say ";
            }

            else
            {
                MessageBox.Show("You are not connected yet.");
            }
        }

        private void connectToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!connection.Connected)
            {
                connection.Connect(txfIp.Text, Int32.Parse(txfPort.Text));

                if (txfName.Text != "")
                {
                    String message = "/setname " + txfName.Text;

                    connection.Send(Encoding.ASCII.GetBytes(message));
                    txfName.Text = "";
                }
            }
        }

        private void disconnectToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (connection.Connected)
            {
                connection.Disconnect();
            }
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void ClientForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            disconnectToolStripMenuItem_Click(sender, e);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (connection.Connected)
            {
                if (txfName.Text != "")
                {
                    String message = "/setname " + txfName.Text;

                    connection.Send(Encoding.ASCII.GetBytes(message));
                    txfName.Text = "";
                }
            }

            else
            {
                MessageBox.Show("You are not connected yet.");
            }
        }
    }
}